import {
	Inject
} from 'plugins'
import config from 'config';

@Inject('$scope', '$sce', '$state', '$popbox', 'ui.http', 'ui.dialog', 'ui.api', 'ConfigApiService')
export default class Dictionary {
	constructor($scope, $sce, $state, $popbox, http, dialog, api, service) {
		var q = $scope.q = {};

		var loadData = $scope.loadData = function(params) {
			api.gridLoad({
				name: 'dictionary',
				params: params,
				scope: $scope,
				success: function(data, options) {
					var _scope = this;
					_scope.fields = angular.merge({}, _scope.fields, data.fields);
				}
			});
		};

		var query = $scope.query = function(resetPage) {
			if (resetPage === false || $scope.gridOptions.paginationCurrentPage == 1) {
				loadData(q);
			} else {
				api.gridReset(null, $scope);
			}
		}

		/*
		function addOption(e) {
			var _scope = this;
			var _data = _scope.data;
			$popbox.create({
				target: e,
				template: require('./views/form_option.tpl.html'),
				controller: ['$scope', 'popbox', function(scope, popbox) {
					var data = scope.data = {};
					scope.submitted = false;
					scope.close = function() {
						popbox.close();
					};
					scope.submit = function(valid) {
						scope.submitted = true;
						if (valid) {

							popbox.close();
						}
					}
					scope.interacted = function(field) {
						return scope.submitted || field.$dirty || field.$touched;
					};
				}]
			}).open()
		}

		function removeOption(index) {
			var _scope = this;
			var _data = _scope.data;
			dialog.confirm('确定要删除选中项？').result.then(function(r) {
				if (r) {
					_data.options.splice(index, 1);
				}
			});
		}
		*/

		$scope.fields = {
			// types: {
			// 	'1': '系统级',
			// 	'2': '用户级'
			// },
			types: [{
				id: 1,
				name: '系统级'
			}, {
				id: 2,
				name: '用户级'
			}]
		}

		$scope.add = function() {
			var id = api.getGridSelectedId($scope);

			api.form({
				title: '添加字典字段',
				template: require('./views/form.tpl.html'),
				name: 'dictionary_add',
				// scope: {
				// 	addOption: addOption,
				// 	removeOption: removeOption
				// },
				scope: {
					fields: $scope.fields,
					json: {},
					addJson: service.addJson,
					jsonKeys: service.jsonKeys,
					getJsonValue: service.getJsonValue,
					removeJson: service.removeJson
				},
				beforeSettings: function() {
					var _scope = this;
					service.reset();
					_scope.addJson();
				},
				beforeSubmit: function(data) {
					var _scope = this;
					data.json = service.getResultJson(_scope.json);
				}
			}).then(function() {
				query(false);
			});
		}

		$scope.edit = function() {
			var id = api.getGridSelectedId($scope);

			api.form({
				title: '修改字典字段',
				template: require('./views/form.tpl.html'),
				name: 'dictionary_edit',
				// scope: {
				// 	addOption: addOption,
				// 	removeOption: removeOption
				// },
				scope: {
					fields: $scope.fields,
					json: {},
					_temp: {},
					addJson: function() {
						var _scope = this;
						var _temp = _scope._temp;
						service.addJson();
						var keys = service.jsonKeys();
						var key = keys[keys.length - 1];
						_temp[key] = true;
					},
					jsonKeys: service.jsonKeys,
					getJsonValue: service.getJsonValue,
					removeJson: function(key) {
						var _scope = this;
						var _temp = _scope._temp;
						service.removeJson(key);
						_temp[key] = false;
					}
				},
				beforeSettings: function() {
					var _scope = this;
					service.reset();
				},
				resolveWait: http.post({
					name: 'dictionary_item',
					params: {
						id: id
					}
				}),
				resolveAfter: function(data) {
					var _scope = this;
					service.setJsonData(_scope.json, data.json);
				},
				beforeSubmit: function(data) {
					var _scope = this;
					data.json = service.getResultJson(_scope.json);
				}
			}).then(function() {
				query(false);
			});
		}
		$scope.remove = function() {
			var ids = api.getGridSelectedIds($scope);
			dialog.confirm('确定要删除已选择的字典字段？').result.then(function(r) {
				if (r) {
					http.post({
						name: 'dictionary_remove',
						params: {
							ids: ids
						},
						success: function() {
							query(false);
						}
					})
				}
			});
		}
		$scope.start = function() {
			var ids = api.getGridSelectedIds($scope);
			dialog.confirm('确定要启用已选择的字典字段？').result.then(function(r) {
				if (r) {
					http.post({
						name: 'dictionary_start',
						params: {
							ids: ids
						},
						success: function() {
							query(false);
						}
					})
				}
			});
		}
		$scope.stop = function() {
			var ids = api.getGridSelectedIds($scope);
			dialog.confirm('确定要停用已选择的字典字段？').result.then(function(r) {
				if (r) {
					http.post({
						name: 'dictionary_stop',
						params: {
							ids: ids
						},
						success: function() {
							query(false);
						}
					})
				}
			});
		}


		$scope.gridOptions = {
			paginationCurrentPage: api.page.pageNumber,
			paginationPageSize: api.page.pageSize,
			useExternalPagination: true,
			columns: [{
					name: '序号',
					width: 50,
					cellTemplate: '<div class="x-grid-inner">{{(grid.options.paginationCurrentPage - 1) * grid.options.paginationPageSize + (index + 1)}}</div>'
				}, {
					name: '字典表名',
					width: 200,
					field: 'field'
				}, {
					name: '显示名称',
					width: 200,
					field: 'fieldName'
				}, {
					name: '类型',
					width: 150,
					field: 'type',
					cellTemplate: '<div class="x-grid-inner" ng-bind-html="grid.appScope.mapping(grid, row, col, \'types\')"></div>'
				},
				/* {
							name: '枚举值',
							width: 300,
							field: 'json',
							align: 'left',
							cellTemplate: '<div class="x-grid-list-inner" ng-bind-html="grid.appScope.parseJson(grid.getCellValue(row, col))"></div>'
						},*/
				{
					name: '操作',
					width: 100,
					field: 'id',
					cellTemplate: '<div class="x-grid-inner"><span class="btn-text" ng-click="grid.appScope.preview(grid.getCellValue(row, col))">详情</span></div>'
				}
			],
			forceFit: false,
			onRegisterApi: function(api) {
				$scope.api = api;
				api.pagination && api.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
					query(false);
				});
			}

		};

		$scope.mapping = function(grid, row, col, field) {
			return api.mapping({
				grid: grid,
				row: row,
				col: col,
				field: field,
				scope: $scope
			});
		}

		$scope.parseJson = function(jsonStr) {
			var json = JSON.parse(jsonStr);
			var html = [];
			html.push('<ul>');
			for (var key in json) {
				html.push('<li>键：<span class="text-warning">' + key + '</span>，值：<span class="text-info">' + json[key] + '</span></li>')
			}
			html.push('</ul>');
			return html.join('');
		}

		$scope.preview = function(id) {
			api.form({
				title: '字典详情',
				template: require('./views/form_preview.tpl.html'),
				resolveWait: http.post({
					name: 'dictionary_preview',
					params: {
						id: id
					}
				})
			})
		}

		$scope.hasSelected = function() {
			return api.hasGridSelected($scope);
		}
		$scope.hasSelectedRecords = function() {
			return api.hasGridSelectedRecords($scope);
		}

		query();
	}
}